#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/29 19:16
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : ser_sms_template.py
# @Software: PyCharm
# @Desc    :
from rest_framework import serializers
from ssms.models import SMSTemplate, SMSProvider
import json


class SMSTemplateSerializer(serializers.ModelSerializer):
    """
    SMSTemplate序列化器：
    - 新增/更新时校验必填字段
    - 关联SMSProvider的名称显示
    - template_data自动转为JSON格式
    """
    # 显示关联的短信供应商名称（只读）
    sms_provider_name = serializers.CharField(source='sms_provider.sms_name', read_only=True)
    # 时间字段格式化
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = SMSTemplate
        fields = [
            "id", "name", "sms_provider", "sms_provider_name", "sign",
            "template_id", "template_data", "description", "sort_num",
            "is_active", "create_time", "update_time"
        ]
        read_only_fields = ["id", "create_time", "update_time"]

    def validate_name(self, value):
        """校验模板标题唯一性"""
        value = value.strip()
        if not value:
            raise serializers.ValidationError("模板标题不能为空")

        queryset = SMSTemplate.objects.filter(is_delete=0, pt_flag=0)
        if self.instance is None:  # 新增
            if queryset.filter(name=value).exists():
                raise serializers.ValidationError(f"模板标题「{value}」已存在")
        else:  # 更新
            if queryset.exclude(id=self.instance.id).filter(name=value).exists():
                raise serializers.ValidationError(f"模板标题「{value}」已存在")
        return value

    def validate_template_id(self, value):
        """校验模板CODE非空"""
        value = value.strip()
        if not value:
            raise serializers.ValidationError("模板CODE不能为空")
        return value

    def validate_sign(self, value):
        """校验签名非空"""
        value = value.strip()
        if not value:
            raise serializers.ValidationError("模板签名不能为空")
        return value

    # def validate_template_data(self, value):
    #     """校验模板变量为JSON格式（允许空字符串，实际发送时需补充）"""
    #     if not value:
    #         return value  # 允许空，发送时需传参
    #     try:
    #         json.loads(value)  # 验证JSON格式
    #     except json.JSONDecodeError:
    #         raise serializers.ValidationError("模板变量必须为JSON格式（如{\"code\":\"123456\"}）")
    #     return value

    def validate_sms_provider(self, value):
        """校验关联的短信供应商是否有效"""
        if value.is_delete == 1 or value.pt_flag == 1:
            raise serializers.ValidationError(f"短信供应商「{value.sms_name}」已失效，请选择其他供应商")
        return value

    def validate(self, data):
        """新增场景必传字段校验"""
        if self.instance is None:  # 新增
            required_fields = ["name", "sms_provider", "sign", "template_id"]
            missing = [f for f in required_fields if f not in data]
            if missing:
                raise serializers.ValidationError(f"缺少必填字段：{', '.join(missing)}")
        return data